package stack;

//                                 模拟实现栈
public class MyStack {
    private String[] arr;
    private int size;

    //入栈操作
    public void push(String elem){
        //考虑扩容操作
        if (size == arr.length){
            resize();
        }
        arr[size] = elem;
        size++;
    }
    //取栈顶元素
    public String peek(){
        if (size == 0){
            throw new RuntimeException("stack is empty");
        }
        String elem = arr[size - 1];
        return elem;
    }
    //出栈操作
    public String pop(){
        //特殊情况
        if (size == 0){
            throw new RuntimeException("stack is empty");
        }
        String elem = arr[size - 1];
        size--;
        return elem;
    }

    //扩容操作
    public void resize(){
        String[] newArr = new String[(int)(arr.length * 1.5)];
        for (int i = 0; i < arr.length; i++){
            newArr[i] = arr[i];
        }
        arr = newArr;
    }

    //构造方法
    public MyStack(){
        this.arr = new String[10];
        size = 0;
    }
    public MyStack(int capacity){
        if (capacity <= 10){
            capacity = 10;
        }
        this.arr = new String[capacity];
        size = 0;
    }

    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push("apple");
        stack.push("banana");
        stack.push("prape");
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}
